package com.imooc.sell.controller;

import com.imooc.sell.VO.wang.InParamVO.*;
import com.imooc.sell.VO.wang.OutParamVO.*;
import com.imooc.sell.dao.UserDao;
import com.imooc.sell.dataobject.OrderDetail;
import com.imooc.sell.dataobject.OrderMaster;
import com.imooc.sell.dataobject.User;
import com.imooc.sell.dto.OrderDTO;
import com.imooc.sell.enums.ErrorEnum;
import com.imooc.sell.expection.SellExpection;
import com.imooc.sell.service.OrderService;
import com.imooc.sell.utils.wang.OutUtils;
import com.imooc.sell.utils.wang.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 和订单操作相关的Controller
 *
 * @author wang
 */
@CrossOrigin
@Slf4j
@RestController
@RequestMapping(value = "/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private UserDao userDao;

    /**
     * 通过openid查询用户的基本信息
     *
     * @param openIdVO 用户openid对象
     * @return Json字符串
     */
    @RequestMapping(value = "/baseuserinfo")
    public String getBaseUserInfo(@RequestBody OpenIdVO openIdVO) throws SellExpection {
        UserInfoOutVO userInfoOutVO = new UserInfoOutVO();

        String openid = openIdVO.getOpenid();
        //非法请求
        if (openid == null || "".equals(openid)) {
            log.error("[获取用户基本信息],openid={}", openid);
            return ResultUtils.reFailJson();
        }

        User user;
        //首单用户

        try {
            user = orderService.getUserBaseInfo(openid);
        } catch (SellExpection se) {
            return ResultUtils.reFailJson(2, "首次使用的用户信息不存在");
        }

        //回头客
        userInfoOutVO.setName(user.getName());
        userInfoOutVO.setPhone(user.getPhone());
        return ResultUtils.reSuccessJson(userInfoOutVO);
    }

    /**
     * 创建订单（提交订单）
     *
     * @param orderSaveVO 提交订单传入参数对象
     * @return Json字符串
     * @author wang
     */
    @RequestMapping(value = "/ordersave")
    public String orderSave(@RequestBody OrderSaveVO orderSaveVO) {
        System.out.println(orderSaveVO);
        OrderSaveOutVO orderSaveOutVO = new OrderSaveOutVO();
        Date date = new Date();

        if (orderSaveVO == null) {
            return ResultUtils.reFailJson();
        }

        OrderDTO orderDTO = new OrderDTO();
        //构建传入参数orderDTO,用于传入service层
        orderDTO.setOrderId(orderSaveVO.getId());
        orderDTO.setBuyerName(orderSaveVO.getBuyer_name());
        orderDTO.setBuyerPhone(orderSaveVO.getBuyer_phone());
        orderDTO.setBuyerAdderss(orderSaveVO.getBuyer_address());
        orderDTO.setBuyerOpenid(orderSaveVO.getBuyer_openid());
        orderDTO.setOrderAmount(orderSaveVO.getOrder_amount());
        orderDTO.setCreateTime(date);

        //将参数中的商品详情列表转换为OrderDetail的对象列表
        List<OrderDetail> orderDetailList = OutUtils.Foods2OrderDetailList(orderSaveVO.getFoods());
        orderDTO.setOrderDetailList(orderDetailList);


        //调用service层接口
        OrderDTO resultDTO = null;
        try {
            resultDTO = orderService.orderSave(orderDTO);
        } catch (SellExpection se) {
            if (se.getCode().equals(ErrorEnum.ORDER_DETAIL_NULL.getCode())) {
                return ResultUtils.reFailJson(2, "订单详情列表为null");
            } else if (se.getCode().equals(ErrorEnum.PRODUCT_ID_IS_NULL.getCode())) {
                return ResultUtils.reFailJson(3, "订单详情列表中存在空productid");
            } else if (se.getCode().equals(ErrorEnum.PRODUCT_NOT_FOUND.getCode())) {
                return ResultUtils.reFailJson(4, "未查找到指定商品中的一种或多种");
            } else if (se.getCode().equals(ErrorEnum.PRODUCT_STOCK_NOT_ENOUGH.getCode())) {
                return ResultUtils.reFailJson(5, "商品库存不足");
            }
        }

        if (resultDTO == null) {
            return ResultUtils.reFailJson(6, "【提交订单】未知错误");
        }

        //如果用户是新用户，则将其存入到User表中
        if (!checkUser(orderSaveVO.getBuyer_openid())) {
            User user = new User();
            user.setName(orderSaveVO.getBuyer_name());
            user.setPhone(orderSaveVO.getBuyer_phone());
            user.setOpenid(orderSaveVO.getBuyer_openid());
            userDao.save(user);
        }

        orderSaveOutVO.setCreateTime(date);
        orderSaveOutVO.setOrderId(resultDTO.getOrderId());
        return ResultUtils.reSuccessJson(orderSaveOutVO);
    }

    private boolean checkUser(String buyer_openid) {
        boolean flag = false;
        try {
            flag = userDao.getOne(buyer_openid).getName() != null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 支付
     *
     * @param orderIdVO 退款传入的订单Id对象
     * @return json字符串
     * @author wang
     */
    @RequestMapping(value = "/pay")
    public String pay(@RequestBody OrderIdVO orderIdVO) {
        String orderId = orderIdVO.getOrderId();

        //判断参数
        if (orderId == null || "".equals(orderId)) {
            return ResultUtils.reFailJson();
        }

        try {
            orderService.paid(orderId);
        } catch (SellExpection se) {
            return ResultUtils.reFailStatusJudge(se);
        }

        return ResultUtils.reSuccessJson();
    }

    /**
     * 退款
     *
     * @param orderIdVO 退款传入的订单Id对象
     * @return json字符串
     * @author wang
     */
    @RequestMapping(value = "/payback")
    public String payBack(@RequestBody OrderIdVO orderIdVO) {
        String orderId = orderIdVO.getOrderId();
        //判断参数
        if (orderId == null || "".equals(orderId)) {
            return ResultUtils.reFailJson();
        }

        try {
            orderService.payBack(orderId);
        } catch (SellExpection se) {
            return ResultUtils.reFailStatusJudge(se);
        }
        return ResultUtils.reSuccessJson();
    }

    /**
     * 取消订单
     *
     * @param orderIdVO 取消订单所需的参数对象
     * @return json字符串
     */
    @RequestMapping(value = "/cancel")
    public String cancel(@RequestBody OrderIdVO orderIdVO) {
        String orderId = orderIdVO.getOrderId();

        //判断参数
        if (orderId == null || "".equals(orderId)) {
            return ResultUtils.reFailJson();
        }

        OrderDTO resultDTO = null;
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setOrderId(orderId);
        try {
            resultDTO = orderService.cancel(orderDTO);
        } catch (SellExpection se) {
            if (se.getCode().equals(ErrorEnum.ORDER_NOT_EXIST.getCode())) {
                return ResultUtils.reFailJson(2, "订单不存在");
            } else if (se.getCode().equals(ErrorEnum.ORDER_STATUS_ERROR.getCode())) {
                return ResultUtils.reFailJson(3, "订单状态错误，当前订单不允许取消订单");
            } else if (se.getCode().equals(ErrorEnum.ORDER_DETAIL_NULL.getCode())) {
                return ResultUtils.reFailJson(4, "该订单详情为null");
            }
        }

        if (resultDTO == null) {
            return ResultUtils.reFailJson(4, "[取消订单]未知错误");
        }

        return ResultUtils.reSuccessJson();
    }

    /**
     * 查询订单列表(不分页)
     *
     * @param openIdVO 用户的openid
     * @return String json字符串
     */
    @RequestMapping(value = "/orderlist")
    public String findAllOrderList(@RequestBody OpenIdVO openIdVO) {
        OrderListOutVO orderListOutVO = new OrderListOutVO();

        if (openIdVO == null) {
            return ResultUtils.reFailJson();
        }

        //查询用户的所有订单
        List<OrderDTO> orderDTOList = orderService.findAllOrderListByOpenid(openIdVO.getOpenid());
        List<OrderOutVO> orderOutVOList = orderDTOList
                .stream()
                .map(e -> new OrderOutVO(e.getOrderId(),
                        e.getOrderAmount(), e.getOrderStatus(),
                        e.getPayStatus(), e.getBuyerAdderss(), e.getCreateTime()))
                .collect(Collectors.toList());
        orderListOutVO.setOrderList(orderOutVOList);

        return ResultUtils.reSuccessJson(orderListOutVO);
    }

    /**
     * 根据订单号查询对应的订单详情
     *
     * @param orderIdVO 订单 id传入对象
     * @return 订单详情Json串
     */
    @RequestMapping(value = "/detaillist")
    public String findDetailList(@RequestBody OrderIdVO orderIdVO) {
        if (orderIdVO == null) {
            return ResultUtils.reFailJson();
        }
        List<OrderDetail> orderDetailList = orderService.findDetailList(orderIdVO.getOrderId());
        if (orderDetailList == null) {
            return ResultUtils.reFailJson(2, "查询结果为null");
        }
        //将查询数据对应属性赋值给输出对象
        List<DetailOutVO> detailOutVOList = orderDetailList.stream()
                .map(e -> new DetailOutVO(e.getProductId(), e.getProductName(),
                        e.getProductQuantity(), e.getProductPrice(), e.getProductIcon(), e.getCreateTime()))
                .collect(Collectors.toList());
        OrderDTO od = orderService.findOneOrderMaster(orderIdVO.getOrderId());
        DetailListOutVO detailListOutVO = new DetailListOutVO(detailOutVOList,
                od.getPayStatus().toString(),
                od.getOrderStatus().toString());
        detailListOutVO.setAddress(od.getBuyerAdderss());
        return ResultUtils.reSuccessJson(detailListOutVO);
    }

    /***卖家端****/

    /**
     * 商家取消订单
     *
     * @param orderIdVO 订单id
     * @return Josn字符串
     */
    @RequestMapping(value = "/sellercancel")
    public String sellerCancel(@RequestBody OrderIdVO orderIdVO) {
        String orderId = orderIdVO.getOrderId();

        //判断参数
        if (orderId == null || "".equals(orderId)) {
            return ResultUtils.reFailJson();
        }

        OrderDTO resultDTO = null;
        try {
            resultDTO = orderService.sellerCancel(orderId);
        } catch (SellExpection se) {
            if (se.getCode().equals(ErrorEnum.ORDER_NOT_EXIST.getCode())) {
                return ResultUtils.reFailJson(2, "订单不存在");
            } else if (se.getCode().equals(ErrorEnum.ORDER_STATUS_ERROR.getCode())) {
                return ResultUtils.reFailJson(3, "订单状态错误，当前订单不允许取消订单");
            } else if (se.getCode().equals(ErrorEnum.PAY_STATUS_ERROR.getCode())) {
                return ResultUtils.reFailJson(4, "订单支付状态错误，当前订单不允许取消订单");
            } else if (se.getCode().equals(ErrorEnum.ORDER_DETAIL_NULL.getCode())) {
                return ResultUtils.reFailJson(5, "该订单详情为null");
            }
        }

        if (resultDTO == null) {
            return ResultUtils.reFailJson(6, "[取消订单]未知错误");
        }
        String json = ResultUtils.reSuccessJson();
        return null;
    }

    /**
     * 商家是否同意退款
     *
     * @param agreePayBackVO 传入参数对象
     * @return Json字符串
     */
    @RequestMapping(value = "/agreepayback")
    public String agreePayBack(@RequestBody AgreePayBackVO agreePayBackVO) {

        //判断传入参数
        if (agreePayBackVO == null) {
            return ResultUtils.reFailJson();
        }

        try {
            orderService.agreePayBack(agreePayBackVO.getOrderId(), agreePayBackVO.isAgree());
        } catch (SellExpection se) {
            return ResultUtils.reFailStatusJudge(se);
        }

        return ResultUtils.reSuccessJson();
    }


/*********************返回视图*****************************/

    /**
     * 通过openid查询用户的基本信息,并返回视图
     *
     * @param openIdVO 用户openid对象
     * @return model视图
     * @author wang
     */
    @RequestMapping(value = "/admin/baseuserinfo")
    public ModelAndView getBaseUserInfo(@RequestBody OpenIdVO openIdVO, Model model) throws SellExpection {
        UserInfoOutVO userInfoOutVO = new UserInfoOutVO();

        String openid = openIdVO.getOpenid();
        //判断openid是否合理
        if (openIdVO.getOpenid() == null || "".equals(openIdVO.getOpenid())) {
            log.error("[获取用户openid],openid={}", openid);
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将openid存入返回视图
        model.addAttribute("openid", openIdVO.getOpenid());

        User user;
        //首单用户
        try {
            user = orderService.getUserBaseInfo(openid);
        } catch (SellExpection se) {
            return ResultUtils.reFailModelAndView(2, "首次使用的用户信息不存在", "/wang/error/404", model);
        }

        //回头客
        userInfoOutVO.setName(user.getName());
        userInfoOutVO.setPhone(user.getPhone());
        return ResultUtils.reSuccessModelAndView("userinfo", userInfoOutVO, "/wang/success/userinfo", model);
    }

    /**
     * 创建订单（提交订单）
     *
     * @param orderSaveVO 提交订单传入参数对象
     * @return 视图对象
     * @author wang
     */
    @RequestMapping(value = "/admin/ordersave")
    public ModelAndView orderSave(@RequestBody OrderSaveVO orderSaveVO, Model model) {
        OrderSaveOutVO orderSaveOutVO = new OrderSaveOutVO();

        if (orderSaveVO.getOpenid() == null || "".equals(orderSaveVO.getOpenid())) {
            log.error("[获取用户openid],openid={}", orderSaveVO.getOpenid());
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将openid存入返回视图
        model.addAttribute("openid", orderSaveVO.getOpenid());

        OrderDTO orderDTO = new OrderDTO();
        //构建传入参数
        orderDTO.setBuyerName(orderSaveVO.getBuyer_name());
        orderDTO.setBuyerPhone(orderSaveVO.getBuyer_phone());
        orderDTO.setBuyerAdderss(orderSaveVO.getBuyer_address());
        orderDTO.setBuyerOpenid(orderSaveVO.getBuyer_openid());
        orderDTO.setOrderAmount(orderSaveVO.getOrder_amount());
        Date date = new Date();
        orderDTO.setCreateTime(new Date());

        //将参数中的商品详情列表转换为OrderDetail的对象列表
        List<OrderDetail> orderDetailList = OutUtils.Foods2OrderDetailList(orderSaveVO.getFoods());
        orderDTO.setOrderDetailList(orderDetailList);


        //调用service层接口提交订单
        OrderDTO resultDTO = new OrderDTO();
        try {
            resultDTO = orderService.orderSave(orderDTO);
        } catch (SellExpection se) {
            if (se.getCode().equals(ErrorEnum.ORDER_DETAIL_NULL.getCode())) {
                return ResultUtils.reFailModelAndView(2, "订单详情列表为null", model);
            } else if (se.getCode().equals(ErrorEnum.PRODUCT_ID_IS_NULL.getCode())) {
                return ResultUtils.reFailModelAndView(3, "订单详情列表中存在空productid", model);
            } else if (se.getCode().equals(ErrorEnum.PRODUCT_NOT_FOUND.getCode())) {
                return ResultUtils.reFailModelAndView(4, "未查找到指定商品中的一种或多种", model);
            } else if (se.getCode().equals(ErrorEnum.PRODUCT_STOCK_NOT_ENOUGH.getCode())) {
                return ResultUtils.reFailModelAndView(5, "商品库存不足", model);
            }
        } catch (Exception e) {
            return ResultUtils.reFailModelAndView(6, "【提交订单】存储到数据库失败", model);
        }

        //设置返回参数
        //此处无法获取记录的时间，在此函数中查询在本函数中插入的记录，貌似获取不到时间，因为时间是数据库default创建的，需要自己创建
        orderSaveOutVO.setCreateTime(date);
        orderSaveOutVO.setOrderId(resultDTO.getOrderId());
        return ResultUtils.reSuccessModelAndView("order", orderSaveOutVO, "/wang/success/order", model);
    }

    /**
     * 支付
     *
     * @param orderIdVO 退款传入的订单Id对象
     * @return 视图对象
     * @author wang
     * @author wang
     */
    @RequestMapping(value = "/admin/pay")
    public ModelAndView pay(@RequestBody OrderIdVO orderIdVO, Model model) {
        String orderId = orderIdVO.getOrderId();

        //判断参数
        if (orderIdVO.getOpenid() == null || "".equals(orderIdVO.getOpenid())) {
            log.error("[获取用户openid],openid={}", orderIdVO.getOpenid());
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将openid存入返回视图
        model.addAttribute("openid", orderIdVO.getOpenid());

        try {
            orderService.paid(orderId);
        } catch (SellExpection se) {
            return ResultUtils.reFailStatusJudgeModel(se, model);
        }

        return ResultUtils.reSuccessModelAndView("/wang/success/paidSuccess", model);
    }

    /**
     * 退款
     *
     * @param orderIdVO 退款传入的订单Id对象
     * @return 视图对象
     * @author wang
     * @author wang
     */
    @RequestMapping(value = "/admin/payBack")
    public ModelAndView payBack(@RequestBody OrderIdVO orderIdVO, Model model) {
        String orderId = orderIdVO.getOrderId();

        //判断参数
        if (orderIdVO.getOpenid() == null || "".equals(orderIdVO.getOpenid())) {
            log.error("[获取用户openid],openid={}", orderIdVO.getOpenid());
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将openid存入返回视图
        model.addAttribute("openid", orderIdVO.getOpenid());

        try {
            orderService.payBack(orderId);
        } catch (SellExpection se) {
            return ResultUtils.reFailStatusJudgeModel(se, model);
        }

        return ResultUtils.reSuccessModelAndView("/wang/success/paybackSuccess", model);
    }

    /**
     * 商家取消订单()
     *
     * @param orderIdVO 取消订单所需的参数对象
     * @return 视图对象
     * @author wang
     */
    @RequestMapping(value = "/admin/cancel")
    public ModelAndView cancel(@RequestBody OrderIdVO orderIdVO, Model model) {
        String orderId = orderIdVO.getOrderId();

        //判断参数
        if (orderIdVO.getOpenid() == null || "".equals(orderIdVO.getOpenid())) {
            log.error("[获取用户openid],openid={}", orderIdVO.getOpenid());
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将用户openid存入返回视图
        model.addAttribute("openid", orderIdVO.getOpenid());

        OrderDTO resultDTO = null;
        try {
            resultDTO = orderService.sellerCancel(orderId);
        } catch (SellExpection se) {
            if (se.getCode().equals(ErrorEnum.ORDER_NOT_EXIST.getCode())) {
                return ResultUtils.reFailModelAndView(2, "订单不存在", model);
            } else if (se.getCode().equals(ErrorEnum.ORDER_STATUS_ERROR.getCode())) {
                return ResultUtils.reFailModelAndView(3, "订单状态错误，当前订单不允许取消订单", model);
            } else if (se.getCode().equals(ErrorEnum.ORDER_DETAIL_NULL.getCode())) {
                return ResultUtils.reFailModelAndView(4, "该订单详情为null", model);
            }
        }

        if (resultDTO == null) {
            return ResultUtils.reFailModelAndView(5, "[取消订单]未知错误", model);
        }

        return ResultUtils.reSuccessModelAndView("/wang/success/cancelSuccess", model);
    }

    /**
     * 查询订单列表(不分页)
     *
     * @param openIdVO 用户的openid
     * @return 视图对象
     * @author wang
     */
    @RequestMapping(value = "/admin/orderlist")
    public ModelAndView findAllOrderList(@RequestBody OpenIdVO openIdVO, Model model) {
        OrderListOutVO orderListOutVO = new OrderListOutVO();

        if (openIdVO.getOpenid() == null || "".equals(openIdVO.getOpenid())) {
            log.error("[获取用户openid],openid={}", openIdVO.getOpenid());
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将用户openid存入返回视图
        model.addAttribute("openid", openIdVO.getOpenid());

        //查询用户的所有订单
        List<OrderDTO> orderDTOList = orderService.findAllOrderListByOpenid(openIdVO.getOpenid());
        List<OrderOutVO> orderOutVOList = orderDTOList
                .stream()
                .map(e -> new OrderOutVO(e.getOrderId(),
                        e.getOrderAmount(), e.getOrderStatus(),
                        e.getPayStatus(), e.getBuyerAdderss(), e.getCreateTime()))
                .collect(Collectors.toList());
        orderListOutVO.setOrderList(orderOutVOList);

        return ResultUtils.reSuccessModelAndView("orderlist", orderListOutVO, "/wang/success/orderlist", model);
    }

    /**
     * 根据订单号查询对应的订单详情
     *
     * @param orderIdVO 订单 id传入对象
     * @return 视图对象
     * @author wang
     */
    @RequestMapping(value = "/admin/detaillist")
    public ModelAndView findDetailList(@ModelAttribute OrderIdVO orderIdVO, Model model) {
        //判断openid是否存在
        if (orderIdVO.getOpenid() == null || "".equals(orderIdVO.getOpenid())) {
            log.error("[获取用户openid],openid={}", orderIdVO.getOpenid());
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将用户openid存入返回视图
        model.addAttribute("openid", orderIdVO.getOpenid());

        //查询订单详情
        List<OrderDetail> orderDetailList = orderService.findDetailList(orderIdVO.getOrderId());
        if (orderDetailList == null) {
            return ResultUtils.reFailModelAndView(2, "查询结果为null", model);
        }

        //将查询数据对应属性赋值给输出对象
        List<DetailOutVO> detailOutVOList = orderDetailList.stream()
                .map(e -> new DetailOutVO(e.getProductId(), e.getProductName(),
                        e.getProductQuantity(), e.getProductPrice(), e.getProductIcon(), e.getCreateTime()))
                .collect(Collectors.toList());
        DetailListOutVO detailListOutVO = new DetailListOutVO(detailOutVOList, "-1", "-1");
        return ResultUtils.reSuccessModelAndView("detaillist", detailListOutVO, "/wang/success/detaillist", model);
    }

    /***卖家端****/

    /**
     * 商家取消订单
     *
     * @param orderIdVO 订单id
     * @return Josn字符串
     */
    @RequestMapping(value = "/admin/sellercancel")
    public ModelAndView sellerCancel(@ModelAttribute OrderIdVO orderIdVO, Model model) {
        String orderId = orderIdVO.getOrderId();

        //判断参数
        if (orderIdVO.getOpenid() == null || "".equals(orderIdVO.getOpenid())) {
            log.error("[获取用户openid],openid={}", orderIdVO.getOpenid());
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将用户openid存入返回视图
        model.addAttribute("openid", orderIdVO.getOpenid());

        OrderDTO resultDTO = null;
        try {
            resultDTO = orderService.findOneOrderMaster(orderId);
        } catch (SellExpection se) {
            if (se.getCode().equals(ErrorEnum.ORDER_NOT_EXIST.getCode())) {
                return ResultUtils.reFailModelAndView(2, "订单不存在", model);
            }
        }

        if (resultDTO == null) {
            return ResultUtils.reFailModelAndView(6, "[取消订单]未知错误", model);
        }

        //跳转到退款接口
        return ResultUtils.reSuccessModelAndView(
                "redirect:http://localhost:8080/sell/pay/admin/refund?openid=" + orderIdVO.getOpenid()
                        + "&orderId=" + orderId + "&orderAmount=" + resultDTO.getOrderAmount(), model);
    }

    /**
     * 商家是否同意退款
     *
     * @param agreePayBackVO 传入参数对象
     * @return Json字符串
     */
    @RequestMapping(value = "/admin/agreepayback")
    public ModelAndView agreePayBack(@ModelAttribute AgreePayBackVO agreePayBackVO, Model model) {
        //判断传入参数
        if (agreePayBackVO.getOpenid() == null || "".equals(agreePayBackVO.getOpenid())) {
            log.error("[获取用户openid],openid={}", agreePayBackVO.getOpenid());
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将用户openid存入返回视图
        model.addAttribute("openid", agreePayBackVO.getOpenid());

        //调用service层判断退款接口
        try {
            orderService.agreePayBack(agreePayBackVO.getOrderId(), agreePayBackVO.isAgree());
        } catch (SellExpection se) {
            return ResultUtils.reFailStatusJudgeModel(se, model);
        }

        return ResultUtils.reSuccessModelAndView("/wang/success/paybackSuccess", model);
    }

    /**
     * 商家是否同意退款
     *
     * @return Json字符串
     */
    @RequestMapping(value = "/admin/agreepayback2")
    public ModelAndView agreePayBack2(@RequestParam String orderId, @RequestParam String openid, Model model) {
        //判断传入参数
        if ("".equals(openid) || openid == null) {
            log.error("[获取用户openid],openid={}", openid);
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将用户openid存入返回视图
        model.addAttribute("openid", openid);

        //调用service层判断退款接口
        try {

            orderService.agreePayBack2(orderId, true);
        } catch (SellExpection se) {
            return ResultUtils.reFailStatusJudgeModel(se, model);
        }

        return ResultUtils.reSuccessModelAndView("/wang/success/paybackSuccess", model);
    }

    /**
     * 查询退款中的订单
     * 根据订单状态查询订单
     * 此处返回的视图需要使用超链接(默认get方式访问),所有为了使用方便，不使用RequestBody(默认post方式请求)
     *
     * @param payBackVO 传入查询分类标准和分页标准
     * @return 订单列表显示视图
     */
    @Deprecated
    @RequestMapping(value = "/admin/findpaybackorderlist")
    public ModelAndView findPaybackOrderList(PayBackVO payBackVO, Model model) {

        //判断传入的openid 是否合理
        if (payBackVO.getOpenid() == null || "".equals(payBackVO.getOpenid())) {
            log.error("[获取用户openid],openid={}", payBackVO.getOpenid());
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将用户openid和需要查询的订单状态(用于返回的分页查询)存入返回视图
        model.addAttribute("openid", payBackVO.getOpenid());

        PageRequest pageRequest = PageRequest.of(payBackVO.getCurrentPage() - 1, payBackVO.getSize());
        //根据订单状态查询订单列表
        Page<OrderDTO> orderDTOPage = orderService.findPayingBackOrderList(pageRequest);
        return ResultUtils.reSuccessModelAndView(payBackVO.getCurrentPage(), payBackVO.getSize(), orderDTOPage, "/wang/success/paybackorderlist", model);
    }

    /**
     * 此处返回的视图需要使用超链接(默认get方式访问),所有为了使用方便，不使用RequestBody(默认post方式请求)
     * 根据订单状态和时间范围查询订单
     *
     * @param orderByStatusVO 传入查询分类标准和分页标准以及时间范围（可以不传，有默认值）
     * @return 订单列表显示视图
     */
    @RequestMapping(value = "/admin/findorderbetween")
    public ModelAndView findOrderBetweenDate(OrderByStatusVO orderByStatusVO,
                                             @RequestParam(value = "startDate", defaultValue = "2018-01-01", required = false) String startDate,
                                             @RequestParam(value = "endDate", defaultValue = "9018-01-01", required = false) String endDate,
                                             Model model) {
        //判断openid是否为空
        if (orderByStatusVO.getOpenid() == null || "".equals(orderByStatusVO.getOpenid())) {
            log.error("[获取用户openid],openid={}", orderByStatusVO.getOpenid());
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将用户openid和查询状态存入返回视图
        model.addAttribute("openid", orderByStatusVO.getOpenid());
        model.addAttribute("byStatusType", orderByStatusVO.getByStatusType());

        Date sDate;
        Date eDate;
        try {
            sDate = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
            eDate = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
        } catch (Exception e) {
            log.error("日期转换失败，请输入正确的日期格式，eg:2018-01-01");
            return ResultUtils.reFailModelAndView(2, "日期格式错误", model);
        }
        PageRequest pageRequest = PageRequest.of(orderByStatusVO.getCurrentPage() - 1, orderByStatusVO.getSize());
        //根据订单状态查询订单列表
        Page<OrderDTO> orderDTOPage = orderService.findAllByOrderStatusAndCreateTimeBetweenOrderByCreateTime(
                orderByStatusVO.getByStatusType(), sDate, eDate, pageRequest);
        return ResultUtils.reSuccessModelAndView(orderByStatusVO.getCurrentPage(), orderByStatusVO.getSize(), orderDTOPage, "/wang/success/orderstatuslist", model);
    }

    /**
     * 此处返回的视图需要使用超链接(默认get方式访问),所有为了使用方便，不使用RequestBody(默认post方式请求)
     * 根据订单状态和时间范围查询订单
     *
     * @param orderByStatusVO 传入查询分类标准和分页标准以及时间范围（可以不传，有默认值）
     * @return 订单列表显示视图
     */
    @RequestMapping(value = "/admin/findcommentorderbetween")
    public ModelAndView findCommentOrderBetweenDate(OrderByStatusVO orderByStatusVO, Model model) {
        //判断openid是否为空
        if (orderByStatusVO.getOpenid() == null || "".equals(orderByStatusVO.getOpenid())) {
            log.error("[获取用户openid],openid={}", orderByStatusVO.getOpenid());
            return ResultUtils.reFailModelAndView(0, "openid为空", "/wang/error/404", model);
        }
        //将用户openid和查询状态存入返回视图
        model.addAttribute("openid", orderByStatusVO.getOpenid());

        Date stDate;
        Date enDate;
        try {
            stDate = new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-01");
            enDate = new SimpleDateFormat("yyyy-MM-dd").parse("9018-01-01");
        } catch (Exception e) {
            log.error("日期转换失败，请输入正确的日期格式，eg:2018-01-01");
            return ResultUtils.reFailModelAndView(2, "日期格式错误", model);
        }

        PageRequest pageRequest = PageRequest.of(orderByStatusVO.getCurrentPage() - 1, orderByStatusVO.getSize());
        //根据订单状态查询订单列表
        Page<OrderDTO> orderDTOPage = orderService.findAllByOrderStatusAndCreateTimeBetweenOrderByCreateTime(
                Short.parseShort("3"), stDate, enDate, pageRequest);
        return ResultUtils.reSuccessModelAndView(orderByStatusVO.getCurrentPage(), orderByStatusVO.getSize(), orderDTOPage, "/wang/success/sellCancel", model);
    }
}
